import { themes } from './model'

// 修改样式
const changeStyle = (obj: any) => {
  for (const key in obj) {
    document.getElementsByTagName('body')[0].style.setProperty(`--${key}`, obj[key])
  }
}

// 改变主题的方法
export const setTheme = (themeName: string, option?: any) => {
  // 如果有主题名称，那么则采用我们定义的主题
  const themeConfig = (themes as any)[themeName]
  const localTheme = localStorage.getItem('theme')
  let themeOption = themeConfig
  if (localTheme && themeName === 'dark' && JSON.parse(localTheme).name === 'dark') {
    themeOption = JSON.parse(localTheme)
  }
  changeStyle({ ...themeOption, ...option })

  localStorage.setItem('theme', JSON.stringify({ name: themeName, ...themeOption, ...option })) // 保存主题到本地，下次进入使用该主题
}
